package com.app.twth.ui.b2bpick.submit;


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityB2bPickSubmitBinding;
import com.app.twth.ui.b2bpick.B2BPickViewModel;
import com.app.twth.ui.b2cpick.B2CPickDetails;
import com.app.twth.ui.b2cpick.submit.B2CPickSubmitAdapter;
import com.app.twth.ui.b2cpick.submit.B2CPickSubmitQr;
import com.app.twth.utils.FastJsonUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.util.List;

/**
 * @describe :
 */
public class B2BPickSubmitActivity extends BaseActivity<ActivityB2bPickSubmitBinding, B2BPickViewModel> {
    private String TAG = getClass().getSimpleName();
    B2CPickSubmitAdapter adapter;
    private int type = 0;


    @Override
    protected void initListener() {
        viewModel.skuBarcodesLiveData.observe(this, data -> {
            binding.tvQty.requestFocus();
            binding.tvQty.setText(1 + "");
        });
        viewModel.skuDetailsLiveData.observe(this, data -> {
            binding.tvCode.requestFocus();
            binding.tvCode.setText("");
            binding.tvQty.setText("");
            bottomLayoutBinding.tvHint.setText("");
            adapter.setData(data, 0);
        });
        viewModel.b2CPickSubmitLiveData.observe(this, data -> {
            Intent intent = new Intent();
            intent.putExtra("data", data);
            setResult(RESULT_OK, intent);
            finish();

        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    protected String setTitle() {
        return "Pick(Submit)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext(getString(R.string.submit));

        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        viewModel.pickSubmitQrLiveData.setValue((B2CPickSubmitQr) bundle.getSerializable("B2CPickSubmitQr"));
        String str = bundle.getString("data");
        if (!Utils.isEmpty(str)) {
            viewModel.skuDetailsLiveData.setValue(FastJsonUtil.getObjects(str, B2CPickDetails.SkuDetailListDTO.class));
        }

        binding.tvCode.requestFocus();
        binding.tvCode.setOnEditorActionListener(EnterListenter);
        adapter = new B2CPickSubmitAdapter(this, viewModel.skuDetailsLiveData.getValue());
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerview.setLayoutManager(layoutManager1);
        binding.recyclerview.setAdapter(adapter);

        binding.tvCode.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvQty.setOnFocusChangeListener(onFocusChangeListener);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                setScan();
                break;
            case R.id.tv_reset:
                binding.tvCode.setText("");
                bottomLayoutBinding.tvHint.setText("");
                break;
            case R.id.iv_qty:
                String ctn = binding.tvQty.getText().toString();
                if (Utils.isEmpty(ctn)) {
                    binding.tvQty.setText("0");
                } else {
                    int num = Integer.parseInt(ctn);
                    if (num > 1) {
                        binding.tvQty.setText(num - 1 + "");
                    } else {
                        binding.tvQty.setText(0 + "");
                    }
                }
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                String code = binding.tvCode.getText().toString();
                if (Utils.isEmpty(code)) {
                    ToastUtil.showToast(getString(R.string.scan_sku_barcode_lower));
                    return;
                }
                String qty = binding.tvQty.getText().toString();
                if (Utils.isEmpty(qty)) {
                    ToastUtil.showToast("Please input quantity");
                    return;
                }
                if (Integer.parseInt(qty) < 1) {
                    ToastUtil.showToast("Please input quantity");
                    return;
                }

                viewModel.pickSubmitQrLiveData.getValue().setBarcode(code);
                viewModel.pickSubmitQrLiveData.getValue().setPickedQty(Integer.parseInt(qty));
                viewModel.b2cPickSubmit();
                break;
        }
    }

    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                switch (v.getId()) {
                    case R.id.tv_code:
                        type = 0;
                        break;
                    case R.id.tv_qty:
                        type = 1;
                        break;
                }
            } else {
                type = 0;
            }
        }
    };
    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCode.getText().toString();
                binding.tvCode.setText(barcodeStr);
                showHint("");
                viewModel.getInfoByBarcode(barcodeStr);
            }
            return false;
        }
    };

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        judgeSku();
    }

    private void judgeSku() {
        new AsyncTask<String, Integer, Integer>() {

            @Override
            protected Integer doInBackground(String... strings) {
                switch (type) {
                    case 0:
                        if (viewModel.skuBarcodesLiveData.getValue() != null) {
                            if (barcodeStr.equalsIgnoreCase(viewModel.skuBarcodesLiveData.getValue().getSku())) {
                                return 0;//扫描的是同一个SKU
                            }
                            List<String> barcodes = viewModel.skuBarcodesLiveData.getValue().getBarcodeList();
                            if (barcodes != null) {
                                for (String barcode : barcodes) {
                                    if (barcodeStr.equalsIgnoreCase(barcode)) {//扫描的是barcode
                                        return 0;//扫描的是同一个barcode
                                    }
                                }
                            }
                        }
                        return 6;
                    case 1:
                        if (viewModel.skuBarcodesLiveData.getValue() != null) {
                            if (barcodeStr.equalsIgnoreCase(viewModel.skuBarcodesLiveData.getValue().getSku())) {
                                return 1;
                            }
                            List<String> barcodes = viewModel.skuBarcodesLiveData.getValue().getBarcodeList();
                            if (barcodes != null) {
                                for (String barcode : barcodes) {
                                    if (barcodeStr.equalsIgnoreCase(barcode)) {//扫描的是barcode
                                        return 1;
                                    }
                                }
                            }
                        }
                        return 2;

                }
                return -1;
            }

            @Override
            protected void onPostExecute(Integer i) {
                super.onPostExecute(i);
                switch (i) {
                    case 0:
                        binding.tvCode.setText(barcodeStr);
                        binding.tvQty.requestFocus();
                        break;
                    case 1:
                        String ctn = binding.tvQty.getText().toString();
                        if (Utils.isEmpty(ctn)) {
                            binding.tvQty.setText(1 + "");
                        } else {
                            binding.tvQty.setText((1 + Integer.parseInt(ctn)) + "");
                        }
                        break;
                    case 2:
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                        break;
                    case 6:
                        binding.tvCode.setText(barcodeStr);
                        showHint("");
                        viewModel.getInfoByBarcode(barcodeStr);
                        break;
                }

            }
        }.execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
